using System;
using Extensibility;
using EnvDTE;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Xml.Serialization;
using System.Xml;
using System.Text.RegularExpressions;

using Evaluant.Uss.Xmi;

//#if EUSS11
//#else
//using System.Collections.Generic;
//using Microsoft.VisualStudio.CommandBars;
//#endif

namespace EussWeavingAddIn
{
    /// <summary>The object for implementing an Add-in.</summary>
    /// <seealso class='IDTExtensibility2' />
    /// 
    [GuidAttribute("481B1CCD-0924-476E-97E7-67B927A79ED4"), ProgId("Euss")]
    public class Connect : IDTExtensibility2, IDTCommandTarget
    {
		#region Fields

        private SolutionEvents _solutionEvents;
        private BuildEvents _buildEvents;

        private ArrayList _projects;

		private DTE _applicationObject;
		private AddIn _addInInstance;

		private const string EUSSPROCESSINSTRUTION = "/processing-instruction('evaluant-application')";
		
#if EUSS11
		private static string EUSS_INSTALLATION_DIR_KEY = "SOFTWARE\\Evaluant\\EUSS for .Net 1.1";
#else
		private static string EUSS_INSTALLATION_DIR_KEY = "SOFTWARE\\Evaluant\\EUSS for .Net 2.0";
#endif
		
		private const string EUSSPANENAME = "Euss";
		private const string WEAVINGMODELMSO = "EUSS.WeavingModel";
		private const string SQLMAPPERMSO = "EUSS.Mapping";
		private const string DOMAINMODELMSO = "EUSS.GenerationModel";
		private const string SQLMAPPEROPTIONMSO = "EUSS.MappingOptions";

		#endregion

        #region Custom methods

        /// <summary>
        /// Gets the named property.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        private string GetNamedProperty(EnvDTE.Properties properties, string propertyName)
        {
            foreach (EnvDTE.Property prop in properties)
            {
                if (prop.Name == propertyName)
                {
                    return prop.Value as string;
                }
            }

            return null;
        }

        private string WeaveFile(string weavingFile, string dllFullName, string pdbModelFile)
        {
            string appName = GetWeaverFullName();

            if (appName == String.Empty)
                throw new Exception("Cannot find PersistenceManagerWeaver tool");

            System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
            startinfo.FileName = appName;
            string xml = "/xml:\"" + weavingFile + "\"";
            string dll = "/dll:\"" + dllFullName + "\"";
			string pdb = "/pdb:\"" + pdbModelFile + "\"";
            startinfo.Arguments = " " + xml + " " + dll + " " + pdb + @" /verbose";
            startinfo.UseShellExecute = false;
            startinfo.RedirectStandardOutput = true;
            startinfo.CreateNoWindow = true;

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo = startinfo;
			
			p.Start();

            return p.StandardOutput.ReadToEnd();
        }

		private ArrayList GetWeavingFiles(EnvDTE.Project project)
		{
			ArrayList files = new ArrayList();

			foreach(EnvDTE.ProjectItem item in project.ProjectItems)
			{
                if (item.Name.LastIndexOf(".") != -1 && item.Document != null)
                {
                    string extension = item.Name.Substring(item.Name.LastIndexOf("."));
                    if (extension == ".xml")
                    {
                        XmlDocument doc = new XmlDocument();
						TextReader reader = new StreamReader(item.Document.FullName);
						string fileStr = reader.ReadToEnd();
						fileStr = Converter.DeleteDTD(fileStr);
						fileStr = Converter.DeleteNamespacePowerDesigner(fileStr);
						fileStr = Converter.DeleteSchema(fileStr);

                        doc.Load(new StringReader(fileStr));
                        if (this.GetProgId(doc) == WEAVINGMODELMSO)
                            files.Add(item.Document.FullName);

						reader.Close();
                    }
                }
			}
			return files;
		}

		private ArrayList GetModelFiles(Project project)
		{
			ArrayList files = new ArrayList();

			foreach(EnvDTE.ProjectItem item in project.ProjectItems)
			{
				if (item.Name.LastIndexOf(".") != -1 && item.Document != null)
				{
					string extension = item.Name.Substring(item.Name.LastIndexOf("."));
					if (extension == ".xml")
					{


						XmlDocument doc = new XmlDocument();
						TextReader reader = new StreamReader(item.Document.FullName);
						string fileStr = reader.ReadToEnd();
						fileStr = Converter.DeleteDTD(fileStr);
						fileStr = Converter.DeleteNamespacePowerDesigner(fileStr);
						fileStr = Converter.DeleteSchema(fileStr);

						doc.Load(new StringReader(fileStr));
						if (this.GetProgId(doc) == DOMAINMODELMSO)
							files.Add(item.Document.FullName);
					}
				}
			}
			return files;
		}

        /// <summary>
        /// Iterates throught project items to find all mapping option files.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <returns></returns>
		private ArrayList GetOptionFiles(EnvDTE.Project project)
		{
			ArrayList items = GetProjectsItems(project.ProjectItems);
			ArrayList optionsFiles = new ArrayList();

			foreach(EnvDTE.ProjectItem item in items)
			{
                string path = GetNamedProperty(item.Properties, "FullPath");
                string extension = GetNamedProperty(item.Properties, "Extension");

                if(extension == ".xml")
				{
					XmlDocument doc = new XmlDocument();

					if(item.Document != null)
					{
                        string fileStr = String.Empty;
                        using (TextReader reader = new StreamReader(item.Document.FullName))
                        {
                            fileStr = reader.ReadToEnd();
                            fileStr = Converter.DeleteDTD(fileStr);
                            fileStr = Converter.DeleteNamespacePowerDesigner(fileStr);
                            fileStr = Converter.DeleteSchema(fileStr);
                        }

						doc.LoadXml(fileStr);

						if (this.GetProgId(doc) == SQLMAPPEROPTIONMSO)
						{
							optionsFiles.Add(path);
						}
					}
				}
			}

			return optionsFiles;
		}

		private ArrayList GetProjectsItems(EnvDTE.ProjectItems items)
		{
			ArrayList folderItems = new ArrayList();
			ArrayList subFolders = new ArrayList();

			//Getting single items for the current folder
			foreach(EnvDTE.ProjectItem item in items)
			{
				string extension = String.Empty;
				if(item.Name.IndexOf('.') != -1)
					extension = item.Name.Substring(item.Name.LastIndexOf("."));
				if(extension != String.Empty)
				{
					folderItems.Add(item);
				}
				else
				{
					subFolders.Add(item);
				}
			}

			//Getting single items for sub-folders
			if(subFolders.Count > 0)
			{
				foreach(EnvDTE.ProjectItem item in subFolders)
				{	
					ArrayList tmp = GetProjectsItems(item.ProjectItems);
					for(int i = 0; i < tmp.Count; i++)
					{
						ProjectItem pi = (ProjectItem)tmp[i];
						folderItems.Add(pi);
					}
				}
			}
			return folderItems;
		}

        void _buildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
        {
            string s = string.Empty;
        }

        private void buildEvents_OnBuildProjConfigDone(string Project, string ProjectConfig, string Platform, string SolutionConfig, bool Success)
		{
			foreach (EnvDTE.Project project in _applicationObject.Solution.Projects)
			{
				if(File.Exists(project.FileName) && !_projects.Contains(project))
					_projects.Add(project);
			}

			string result = "\n---------- Weaving operation started ----------\n";

			foreach (EnvDTE.Project project in _projects)
			{
				if (Project == project.UniqueName && Success)
				{
                    string dllName = GetNamedProperty(project.Properties, "OutputFileName");
                    string projectDir = GetNamedProperty(project.Properties, "FullPath");
					string projectFullName = project.FullName;

                    string config = String.Empty;

#if EUSS11
					config = SolutionConfig;
#else
					config = SolutionConfig.Split(new char[] { '|' })[0];
#endif

					string binFile = projectDir + @"bin\" + config + @"\" + dllName;
					string objFile = projectDir + @"obj\" + config + @"\" + dllName;

					ArrayList weavingFiles = GetWeavingFiles(project);

					if(weavingFiles.Count > 0)
					{
						foreach(string fileName in weavingFiles)
						{
							try
							{
								if (File.Exists(binFile))
								{
									string pdbModel = binFile.Substring(0, binFile.LastIndexOf("\\"));
									
                                    if(ProjectConfig == "Debug")
									    pdbModel = String.Concat(pdbModel, "\\pdbmodel_Debug.xml");
                                    else
									    pdbModel = String.Concat(pdbModel, "\\pdbmodel_Release.xml");

                                    ReadPdb(objFile, pdbModel);

									string weavingResult = WeaveFile(fileName, binFile, pdbModel);
									//string weavingResult = "No weave";

									WritePdb(binFile, pdbModel);

									File.Copy(binFile, objFile, true);

									string binPdb = binFile.Substring(0, binFile.LastIndexOf("."));
									binPdb = String.Concat(binPdb, ".pdb");

									string objPdb = objFile.Substring(0, objFile.LastIndexOf("."));
									objPdb = String.Concat(objPdb, ".pdb");

									File.Copy(binPdb, objPdb, true);

									result = String.Concat(result, "\n", weavingResult);
								}
							}
							catch (Exception e)
							{
                                System.Diagnostics.Debug.WriteLine(e.ToString());
							}
						}
						
						WriteOnBuildPane(result, true);
					}
				}
			}
        }

		private const string BUILD_PANE_GUID = "{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}";

		private void WriteOnBuildPane(string paneResult, bool activePane)
		{
			Window window = _applicationObject.Windows.Item(Constants.vsWindowKindOutput);
			OutputWindow outputWnd = (OutputWindow)window.Object;

			OutputWindowPane buildPane = null;

			foreach (OutputWindowPane pane in outputWnd.OutputWindowPanes)
			{
				if (pane.Guid == BUILD_PANE_GUID)
				{
					buildPane = pane;
				}
			}

			buildPane.OutputString(paneResult);
			buildPane.Activate();
		}

		#region Solution Events

        private void solutionEvents_ProjectAdded(Project project)
        {
            _projects.Add((EnvDTE.Project)project);
        }

        private void solutionEvents_Opened()
        {
            foreach (EnvDTE.Project project in _applicationObject.Solution.Projects)
            {
                if(File.Exists(project.FileName))
                    _projects.Add(project);
            }
        }

		private void solutionEvents_BeforeClosing()
		{
			_projects.Clear();
		}

        private void solutionEvents_ProjectRemoved(Project project)
        {
            this._projects.Remove((EnvDTE.Project)project);
        }

		#endregion

        private FileInfo[] GetDirsFiles(DirectoryInfo dir)
        {
            ArrayList list = new ArrayList(dir.GetFiles("*.*"));
            DirectoryInfo[] directories = dir.GetDirectories("*.*");
			foreach (DirectoryInfo directoryInfo in directories)
			{
				list.AddRange(this.GetDirsFiles(directoryInfo));
			}

            return (FileInfo[])list.ToArray(typeof(FileInfo));
        }

        private string GetWeaverFullName()
        {
            RegistryKey rk;
            rk = Registry.LocalMachine.OpenSubKey(EUSS_INSTALLATION_DIR_KEY);
			
			if(rk == null)
				throw new Exception("Cannot find the Euss installation directory in registry");
            
			string pmwFile = String.Concat((string)rk.GetValue(@"InstallDir"), "\\PersistenceManagerWeaver.exe");

            if (File.Exists(pmwFile))
                return pmwFile;
			else
				throw new Exception("Cannot find the Euss Weaving application");
        }

		private string GetMappingGeneratorFullName()
		{
			RegistryKey rk;
			rk = Registry.LocalMachine.OpenSubKey(EUSS_INSTALLATION_DIR_KEY);
			
			if(rk == null)
				throw new Exception("Cannot find the Euss installation directory in registry");
            
			string pmwFile = String.Concat((string)rk.GetValue(@"InstallDir"), "\\mapping.exe");

			if (File.Exists(pmwFile))
				return pmwFile;
			else
				throw new Exception("Cannot find the Euss Mapping Generator application");
		}

		private string GetDbTypeConversionFullName()
		{
			RegistryKey rk;
			rk = Registry.LocalMachine.OpenSubKey(EUSS_INSTALLATION_DIR_KEY);
			
			if(rk == null)
				throw new Exception("Cannot find the Euss installation directory in registry");
            
			string dbtypes = String.Concat((string)rk.GetValue(@"InstallDir"), "\\dbtypes.xml");

			if (File.Exists(dbtypes))
				return dbtypes;
			else
				throw new Exception("Cannot find the Euss DbTypes conversion file");
		}

        private string GetProgId(XmlDocument doc)
        {
			string processIns = String.Empty;
			if(doc.SelectSingleNode(EUSSPROCESSINSTRUTION) != null)
				processIns = doc.SelectSingleNode(EUSSPROCESSINSTRUTION).InnerText;
            string[] splittedProcessIns = processIns.Split(new char[1] { '"' });

            bool finded = false;
            foreach (string s in splittedProcessIns)
            {
                if (finded)
                    return s;

                if (s == "progid=")
                    finded = true;
            }
            return string.Empty;
        }

        #endregion

        /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
        public Connect()
        {
        }

        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
        /// <param term='application'>Root object of the host application.</param>
        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
        /// <param term='addInInst'>Object representing this Add-in.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            _applicationObject = (DTE)application;
            _addInInstance = (AddIn)addInInst;

			_projects = new ArrayList();
            Events events1 = this._applicationObject.Events;
            _solutionEvents = events1.SolutionEvents;
            _solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(solutionEvents_Opened);
            _solutionEvents.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(solutionEvents_ProjectAdded);
            _solutionEvents.ProjectRemoved += new _dispSolutionEvents_ProjectRemovedEventHandler(solutionEvents_ProjectRemoved);
			_solutionEvents.BeforeClosing += new _dispSolutionEvents_BeforeClosingEventHandler(solutionEvents_BeforeClosing);
            _buildEvents = events1.BuildEvents;
            _buildEvents.OnBuildProjConfigDone += new _dispBuildEvents_OnBuildProjConfigDoneEventHandler(buildEvents_OnBuildProjConfigDone);
			_buildEvents.OnBuildProjConfigBegin += new _dispBuildEvents_OnBuildProjConfigBeginEventHandler(_buildEvents_OnBuildProjConfigBegin);
            _buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(_buildEvents_OnBuildDone);
        }

        

        /// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
        /// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
        }

        /// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />		
        public void OnAddInsUpdate(ref Array custom)
        {
        }

        /// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnStartupComplete(ref Array custom)
        {
        }

        /// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnBeginShutdown(ref Array custom)
        {
        }

        /// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>
        /// <param term='commandName'>The name of the command to determine state for.</param>
        /// <param term='neededText'>Text that is needed for the command.</param>
        /// <param term='status'>The state of the command in the user interface.</param>
        /// <param term='commandText'>Text requested by the neededText parameter.</param>
        /// <seealso class='Exec' />
        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)
        {

        }

        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {

		}

		private string GetReadWritePdbFullName()
		{
			RegistryKey rk;
			rk = Registry.LocalMachine.OpenSubKey(EUSS_INSTALLATION_DIR_KEY);
			
			if(rk == null)
				throw new Exception("Cannot find the Euss installation directory in registry");
            
			string rwFile = String.Concat((string)rk.GetValue(@"InstallDir"), "\\ReadWritePdb.exe");

			if (File.Exists(rwFile))
				return rwFile;
			else
				throw new Exception("Cannot find the Euss Read / Write Pdb application");
		}

		private void ModifyPdb(string sourceAssembly, string destAssembly)
		{
			string appName = GetReadWritePdbFullName();

			if (appName == String.Empty)
				throw new Exception("Cannot find ReadWritePdb tool");

			System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
			startinfo.FileName = appName;
			string source = " /source:\"" + sourceAssembly + "\"";
			string dest = " /dest:\"" + destAssembly + "\"";
			startinfo.Arguments = source + dest;
			startinfo.UseShellExecute = false;
			startinfo.RedirectStandardOutput = true;
			startinfo.RedirectStandardError = true;
			startinfo.CreateNoWindow = true;

			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo = startinfo;
			
			p.Start();

			p.WaitForExit();

			//p.Kill();
		}

		private void ReadPdb(string sourceAssembly, string destModel)
		{
			string appName = GetReadWritePdbFullName();

			if (appName == String.Empty)
				throw new Exception("Cannot find ReadWritePdb tool");

			System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
			startinfo.FileName = appName;
			string source = " /assembly:\"" + sourceAssembly + "\"";
			string dest = " /model:\"" + destModel + "\"";
			string op = " /r";
			startinfo.Arguments = source + dest + op;
			startinfo.UseShellExecute = false;
			startinfo.RedirectStandardOutput = true;
			startinfo.CreateNoWindow = true;

			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo = startinfo;
			
			p.Start();

			p.WaitForExit();

			//p.Kill();
		}

		private void WritePdb(string destAssembly, string sourceModel)
		{
			string appName = GetReadWritePdbFullName();

			if (appName == String.Empty)
				throw new Exception("Cannot find ReadWritePdb tool");

			System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
			startinfo.FileName = appName;
			string source = " /assembly:\"" + destAssembly + "\"";
			string dest = " /model:\"" + sourceModel + "\"";
			string op = " /w";
			startinfo.Arguments = source + dest + op;
			startinfo.UseShellExecute = false;
			startinfo.RedirectStandardOutput = true;
			startinfo.CreateNoWindow = true;

			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo = startinfo;
			
			p.Start();

			p.WaitForExit();

			//p.Kill();
		}

		private string GenerateMapping(string optionFileName, ref int code)
		{
			string appName = GetMappingGeneratorFullName();
			string dbTypes = GetDbTypeConversionFullName();

			if (appName == String.Empty)
				throw new Exception("Cannot find MappingGenerator tool");
			if (dbTypes == String.Empty)
				throw new Exception("Cannot find DbTypes conversion file");

			System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
			startinfo.FileName = appName;

            string outFilename = Path.Combine(Path.GetDirectoryName(optionFileName), Path.GetFileNameWithoutExtension(optionFileName) + ".eum.xml");
            string options = String.Format(" /options:\"{0}\" /out:\"{1}\"", optionFileName, outFilename );
			startinfo.Arguments = options;
			
            startinfo.UseShellExecute = false;
			startinfo.RedirectStandardOutput = true;
			startinfo.RedirectStandardError = true;
			startinfo.CreateNoWindow = true;

			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo = startinfo;
			
			p.Start();

			p.WaitForExit();

			code = p.ExitCode;

			string result = string.Empty;
            string tmp = String.Empty;

			switch(code)
			{
                case 6:
                case 0:
                    result = outFilename;
                    tmp = String.Empty;
                    while ((tmp = p.StandardOutput.ReadLine()) != null)
                        result = tmp;
                    break;
                case 2:
					result = p.StandardOutput.ReadLine();
					break;
				case 4 :
					result = p.StandardOutput.ReadLine();
					while((tmp = p.StandardOutput.ReadLine()) != null)
						result = tmp;
					break;
				case 8:
					result = p.StandardOutput.ReadToEnd();
					break;
			}

			return result;
		}

		private void _buildEvents_OnBuildProjConfigBegin(string Project, string ProjectConfig, string Platform, string SolutionConfig)
		{
			foreach (EnvDTE.Project project in _applicationObject.Solution.Projects)
			{
				if (Project == project.UniqueName)
				{
					string result = "\n---------- Generating Mapping Files ----------\n";

					string projectDir = GetNamedProperty(project.Properties, "OutputFileName");
                    string dllName = GetNamedProperty(project.Properties, "FullPath");

					ArrayList weavingFiles = GetWeavingFiles(project);
					if(weavingFiles.Count > 0)
					{
						string binFile = projectDir + @"bin\" + SolutionConfig + @"\" + dllName;
						string objFile = projectDir + @"obj\" + SolutionConfig + @"\" + dllName;
						string binPdb = binFile.Substring(0, binFile.LastIndexOf('.'));
						binPdb = String.Concat(binPdb, ".pdb");
						string objPdb = objFile.Substring(0, objFile.LastIndexOf('.'));
						objPdb = String.Concat(objPdb, ".pdb");

						File.Delete(binFile);
						File.Delete(binPdb);
						File.Delete(objFile);
						File.Delete(objPdb);
					}

					ArrayList optionFiles = GetOptionFiles(project);

					foreach(string option in optionFiles)
					{
						int code = 0;
						
                        string generatorResult = GenerateMapping(option, ref code);

						switch(code)
						{
                            case 0:
                                project.ProjectItems.AddFromFile(generatorResult);
                                result = String.Concat(result, "Success : the mapping file is generated : ", generatorResult, "\n");
                                break;
                            case 1:
								result = String.Concat(result, "Error : Missing option file argument\n");
								break;
							case 2:
								result = String.Concat(result, "Error : Missing Metadata information\n");
								break;
							case 3:
								result = String.Concat(result, "Error : Cannot find the option file\n");
								break;
							case 4:
								if(generatorResult != String.Empty)
									result = String.Concat(result, "Error : Cannot find the model file\n");
								else
									result = String.Concat(result, "Error : No model file is defined in your Option mapping file\n");
								break;
							case 5:
								result = String.Concat(result, "Error : Cannot find the conversion types file\n");
								break;
							case 6:
								result = String.Concat(result, "Error : the mapping file for the model ", generatorResult ,"is not generated\n");
								break;
							case 8:
								result = string.Concat("Mapping Generation Error :\n", generatorResult);
								break;

						}
					}

					WriteOnBuildPane(result, true);
				}
			}
		}
	}
}